package com.bac.rentmap.web.filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class OriginalRequestUrlFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        try {
            OriginalRequestUrlHolder
                    .setUrl(getCurrentUrl((HttpServletRequest) request));
            chain.doFilter(request, response);
        } finally {
            OriginalRequestUrlHolder.setUrl(null);
        }
    }

    @SuppressWarnings("unchecked")
    private String getCurrentUrl(HttpServletRequest request) {
        StringBuilder res = new StringBuilder();
        res.append(request.getRequestURL());
        Enumeration<String> parameterNames = request.getParameterNames();
        boolean firstParameter = true;
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            String[] parameterValues = request
                    .getParameterValues(parameterName);
            for (String parameterValue : parameterValues) {
                if (firstParameter) {
                    firstParameter = false;
                    res.append("?");
                } else {
                    res.append("&");
                }
                res.append(parameterName + "=" + parameterValue);
            }
        }
        return res.toString();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

}
